  <template>
	  <!-- tn-flex tn-flex-col-center tn-flex-row-center tn-flex-direction-column -->
	<view class="zai-box login-paddingtop tn-flex tn-flex-col-center tn-flex-direction-column" >
		
       <text  style="font-size: 36rpx;">欢迎使用</text>
	   <text style="margin-top: 40rpx;margin-bottom:92rpx; font-size:64rpx;color:#3B54DA;">{{logoTitle}}</text>
	   <tn-form class="login-form" :model="form" ref="form" :errorType="['message']" labelPosition="top">
	       <tn-form-item label="公司名称"  prop="company_name" :borderBottom="false">
	         <tn-input class="company-input" v-model="form.company_name" type="text" placeholder="请输入公司名称" />
	       </tn-form-item>
	       <tn-form-item label="姓名" prop="username" type="text"  :borderBottom="false">
	         <tn-input v-model="form.username" placeholder="请输入姓名"></tn-input>
			</tn-form-item>
			<tn-form-item label="联系方式" type="number" prop="mobile"  :borderBottom="false">
			   <tn-input v-model="form.mobile" placeholder="请输入联系方式"></tn-input>
			   
			</tn-form-item>
			<tn-form-item  prop="sms_code" class="phone-style " :borderBottom="false">
				<tn-input v-model="form.sms_code" class="input" type="number" placeholder="请输入验证码"></tn-input>
				<tn-button class="button" width="202rpx" backgroundColor="#F0F0F0" fontColor="#7F7D8C" :disabled="smsCountDown>0" @click="onSMSSend">{{getSendBtnText}}</tn-button>
			</tn-form-item>
		</tn-form>
		<view  class="footer">
			
		
		<tn-button :loading="loading" shape="round" fontSize="32" fontBold backgroundColor="#3B54DA" fontColor="#FFFFFF" width="282rpx" height="80rpx" @click="onLogin" >进入小程序</tn-button>
		
		
		<tn-button  :plain="true" shape="round" fontSize="28"  backgroundColor="#D5D4D4" fontColor="#7F7D8C" width="282rpx" height="80rpx" @click="onUnauthLogin" >暂不登陆</tn-button>
	
		</view>
		<!-- <tn-button open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">fffff</tn-button> -->
		<!-- open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber" -->
		<myCommonSkeletonVue :showSkeleton="showSkeleton" ></myCommonSkeletonVue>
	
    </view>
 
</template>

<script>
	import { ACCESS_TOKEN,USER_NAME,USER_INFO } from "@/common/util/constants"
	import { mapActions } from "vuex"
    import configService from '@/common/service/config.service.js';
	import myCommonSkeletonVue from "@/components/my-componets/my-common-skeleton.vue";
    export default {
		components:{
			myCommonSkeletonVue
		},
        data() {
            return {
				logoTitle:'',
				form:{},
				shape:'',//round 圆形
				loading: false,
				userName: 'admin',
				password: '123456',
				phoneNo: '',
				smsCode: '',
				showPassword: false, //是否显示明文
				loginWay: 1, //1: 账密，2：验证码
				smsCountDown: 0,
				smsCountInterval: null,
				toggleDelay: false,
				version:'',
				//第三方登录相关信息
				thirdType:"",
				thirdLoginInfo:"",
				thirdLoginState:false,
				bindingPhoneModal:false,
				thirdUserUuid:'',
				url: {
					bindingThirdPhone: '/sys/thirdLogin/bindingThirdPhone'
				},
				showSkeleton:true,
            };
        },
		onLoad:function(e){
			console.log('login options',e)
			
			let token = uni.getStorageSync(ACCESS_TOKEN);
			
			let launchOptions = uni.getLaunchOptionsSync();
			console.log('login onLoad getLaunchOptionsSync',launchOptions,token)
			
			this.userId = '';
		
			if(e&&e.user_id){
				this.userId = e.user_id;
			} else if(launchOptions.query&&launchOptions.query.user_id){
				this.userId = launchOptions.query.user_id;
			}
			console.log('this.userid',this.userId)
			
			// #ifdef APP-PLUS
			var that=this
			plus.runtime.getProperty( plus.runtime.appid, function ( wgtinfo ) {
				that.version=wgtinfo.version
			});
			// #endif
			// if(token){
			// 	console.log('token 建在',this.showSkeleton,new Date().getTime())
			// 	// this.$tip.loaded();
				
			// 	// this.$Router.replaceAll({name:'index'});
			// 	uni.reLaunch({url:'/pages/index/index'});
			// 	//onLoad 里$router可能有些问题
				
				
			// } else {
			// 	let launchOptions = uni.getLaunchOptionsSync();
			// 	console.log('token 没了',this.showSkeleton,launchOptions)
			// 	if(launchOptions.referrerInfo&&launchOptions.referrerInfo.appId){
				
					//公众号进来的
					// this.$tip.loading()
					uni.login({
						success: async (res) => {
							
							console.log('wexinlogin',res.code)
							this.loginByManage({code:res.code,type:1}).then(res => {
								this.$tip.loaded();
								console.log('wexinlogin res',res)
								if(res.data.status == 200) {
									
									
									// this.$Router.replaceAll({name:'index'});
									uni.reLaunch({url:'/pages/index/index'});
								} else {//不是b端客户
									if(token){
										
										let userInfo = uni.getStorageSync(USER_INFO);
										console.log('不是绑定客户',token,userInfo)
										if(userInfo&&userInfo.role_id == 1) {
											uni.clearStorageSync();
											this.showSkeleton = false;
											this.getAppLogoData()
										} else if(userInfo){
											uni.reLaunch({url:'/pages/index/index'});
										}
									} else{
										this.showSkeleton = false;
										this.getAppLogoData()
									}
									
									
								}
							})
						},
						fail: (err) => {
							this.$tip.loaded();
							this.$tip.alert('请重新登陆微信')
							console.log('login fail:', err);
						}
					})
				// } else {
					// this.showSkeleton = false;
				// }
			// }
		
			
		},
		onUnload() {
			this.showSkeleton = false;
		},
		computed: {
		      isSendSMSEnable() {
		        return this.smsCountDown <= 0 && this.phoneNo.length > 4;
		      },
		      getSendBtnText() {
		        if (this.smsCountDown > 0) {
		          return this.smsCountDown + '秒后发送';
		        } else {
		          return '发送验证码';
		        }
		      },
		      // canSMSLogin() {
		      //   return this.username.length > 4 && this.smsCode.length > 4;
		      // },
		      // canPwdLogin() {
		      //   return this.username.length > 4 && this.password.length > 4;
		      // },
		},
        methods: {
			 ...mapActions([ "mLogin","PhoneLogin","ThirdLogin" ,"loginByManage"]),
			 getAppLogoData(){
				 this.$http.get('/api/system/kernel').then((res) => {
				 	if(res.data.status == 200) {
						this.$store.commit('SET_LOGO_DATA',res.data.data)
						this.logoTitle = res.data.data.web_chinese_name;
				 		this.logoUrl = res.data.data.logo;
				 	}
				 })
			 },
			 getUserInfo(){
				 uni.getUserProfile({
				 					desc: "获取你的昵称、头像、地区及性别",
				 					success: res => {
				 						this.iv = res.iv
				 						this.encryptedData = res.encryptedData
				 										console.log('授权',res)
				 						//this.miniProgramLogin() //授权成功可调用登录接口
				 					},
				 					fail: res => {
										console.log('jujue',res)
				 						//拒绝授权  也可以再次获取最新的code
				 						uni.showToast({
				 							title: "您已拒绝登录",
				 							icon: 'none',
				 							duration: 2000
				 						})
				 						return;
				 					},
				 				})
			 },
			 onGetPhoneNumber(e){
				 console.log('phone',e)
				 return;
				 this.$http.get('/api/system/kernel').then((res)=>{
					 
				 })
				 this.$tip.success('登录成功!')
				 // this.$Router.replaceAll({name:'index'})
				 return;
				this.loginFn().then(res => {  // 微信登录&服务端获取openid
					console.log(res, '接口换取的openid')
					console.log('获取手机号的动态令牌:', e.detail.code) // 动态令牌
					
					//授权手机号之后应该是调用后端接口拿到手机号并存储起来供后台授权。
					//所以在进入小程序时应该有个接口判断该用户是否被授权
					this.getPhoneNumberFn(e.detail.code, res.openid).then(res2 => { // 服务端获取手机号
						if (res2.code == 0) {
							uni.setStorageSync('phoneNumber', res.content.phone_info.phoneNumber)
							uni.showToast({
								title: '登录成功'
							})
						}
					})
				})
			},
			// 服务端接口 - 获取手机号
			getPhoneNumberFn(phoneCode, openId) {
				return new Promise(resolve => {
					getPhoneNumber({
							code:phoneCode,
							openId
						}).then(res => {
							if (res.code !== 0) {
								console.log('获取手机号失败1：', res.msg);
								return
							}
							resolve(res)
						})
						.catch(err => {
							console.log('获取手机号失败2：', err);
						})
				})
			},
			// 服务端接口 - 获取openid 和seesionId
			queryOpenIdFn(code) {
				return new Promise(resolve => {
					queryOpenId({
							code
						}).then(res => {
							if (res.code !== 0) {
								console.log('获取openid失败1：', res.msg);
								return
							}
							uni.setStorageSync('openId', res.content.openid)
							resolve(res.content)
						})
						.catch(err => {
							console.log('获取openid失败2：', err);
						})
				})
			},
			
			
			
			// 微信api : 微信登录
			loginFn() {
				return new Promise((resolve, reject) => {
					uni.login({
						success: async (res) => {	
							this.queryOpenIdFn(res.code).then(res => {
								resolve(res)
							})
						},
						fail: (err) => {
							console.log('login fail:', err);
						}
					})
				})
			},
			onUnauthLogin(){
				this.$Router.replaceAll({name:'index'})
			},
			onLogin: function (){
				console.log('this.form.company_name',this.form.company_name)
					if(!this.form.company_name || this.form.company_name.length==0){
					  this.$tip.toast('请填写公司名称');
					  return;
					}
			        if(!this.form.username || this.form.username.length==0){
			          this.$tip.toast('请填写姓名');
			          return;
			        }
					if(!this.form.sms_code){
					  this.$tip.toast('请填写验证码');
					  return;
					}
			        // if(!this.password || this.password.length==0){
			        //    this.$tip.toast('请填写密码');
			        //   return;
			        // }
			        let loginParams = {
			          username:this.form.username,
			          company_name:this.form.company_name,
					  mobile:this.form.mobile,
					  sms_code:this.form.sms_code,
					  user_id: this.userId
			        }
					this.loading=true;
					this.$tip.loading();
			        this.mLogin(loginParams).then((res) => {
						console.log('resssss',res,res.data.status == 200)
					  this.$tip.loaded();
					  this.loading=false;
			          if(res.data.status == 200){
						 // #ifdef APP-PLUS
						  // this.saveClientId()
						 // #endif
						 // #ifndef APP-PLUS
						  this.$tip.success('登录成功!')
						  this.$Router.replaceAll({name:'index'})
						 // #endif
						}else{
			              this.$tip.alert(res.data.message);
			            }
			        }).catch((err) => {
			          let msg = err || "请求出现错误，请稍后再试"
			          this.loading=false;
					  this.$tip.alert(msg);
			        }).finally(()=>{
					  this.loading=false;
				})
			},
			saveClientId(){
				var info = plus.push.getClientInfo();
				var cid = info.clientid;
				this.$http.get("/sys/user/saveClientId",{params:{clientId:cid}}).then(res=>{
					console.log("res::saveClientId>",res)
					this.$tip.success('登录成功!')
					this.$Router.replaceAll({name:'index'})
				})
			},
			changePassword() {
				this.showPassword = !this.showPassword;
			},
			onSMSSend() {
				//先判断以下前面是否输入
				let smsParams = {};
				smsParams.mobile=this.form.mobile;
				smsParams.smsmode="0";
				 // let checkEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
				let checkPhone = new RegExp(/^[1]([3-9])[0-9]{9}$/);
                if(!smsParams.mobile || smsParams.mobile.length==0){
					this.$tip.toast('请输入手机号');
					return false
				}
				if(!checkPhone.test(smsParams.mobile)){
					this.$tip.toast('请输入正确的手机号');
					return false
				}
				console.log('shoujiyanzhengm ')
				this.$tip.loading()
				this.$http.post("/api/get_code",smsParams).then(res=>{
					this.$tip.loaded()
				  if(res.data.status == 200){
					this.smsCountDown = 60;
					this.startSMSTimer();
				  }else{
					this.smsCountDown = 0;
					this.$tip.alert(res.data.message);
				  }
				});
			  },
			startSMSTimer() {
				this.smsCountInterval = setInterval(() => {
				  this.smsCountDown--;
				  if (this.smsCountDown <= 0) {
					clearInterval(this.smsCountInterval);
				  }
				}, 1000);
			},
			onSMSLogin() {
				let checkPhone = new RegExp(/^[1]([3-9])[0-9]{9}$/);
				
				if(!this.phoneNo || this.phoneNo.length==0){
				  this.$tip.toast('请填写手机号');
				  return;
				}
				if(!checkPhone.test(this.phoneNo)){
					this.$tip.toast('请输入正确的手机号');
					return false
				}
				if(!this.smsCode || this.smsCode.length==0){
				  this.$tip.toast('请填短信验证码');
				  return;
				}
				let loginParams = {
				  mobile:this.phoneNo,
				  captcha:this.smsCode
				};
				this.PhoneLogin(loginParams).then((res) => {
				  console.log("res====》",res)
				  if(res.data.success){
					this.$tip.success('登录成功!')
					this.$Router.replaceAll({name:'index'})
				  }else{
					this.$tip.error(res.data.message);
				  }
				}).catch((err) => {
				  let msg = ((err.response || {}).data || {}).message || err.data.message || "请求出现错误，请稍后再试"
				  this.$tip.error(msg);
				});
			},
			loginSuccess() {
			  // 登陆成功，重定向到主页
			  this.$Router.replace({name:'index'})
			},
			requestFailed(err) {
			  this.$message.warning("登录失败")
			},
        },
		beforeDestroy() {
		    if (this.smsCountInterval) {
		        clearInterval(this.smsCountInterval);
		    }
		},
    }
</script>

<style lang="scss" scoped>
    .login-paddingtop {
        padding-top: 258rpx;
		
    }

    .zai-box {
        height: 100vh;
		width: 100%;
		// position: relative;
		padding-left: 30rpx;
		padding-right:30rpx;
		.footer{
			display: flex;
			flex-direction: column;
			position: absolute;
			bottom: calc(40rpx + env(safe-area-inset-bottom));
			/deep/.tn-btn--plain{
				margin-top:30rpx
			}
		}
		.login-form{
			width: 100%;
			.company_input{
				/deep/.tn-input-class{
					background-color:#FCFCFF;
				}
			}
			.phone-style{
				display: flex;
				/deep/.tn-form-item--left{
					flex:0!important;
					margin-bottom: 0!important;
				}
				/deep/.tn-form-item--right__content__slot{
					display: flex
				}
				.input{
					width: 100%;
				}
				.button{
					margin-left: 28rpx;
				}
				
				
			}
		}
    }

    .zai-logo {
        width: 200rpx;
        height: 150rpx;
    }



   

</style>
